package name.zeno.qrcode.library

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Fragment
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.JELLY_BEAN_MR1
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.subjects.PublishSubject
import name.zeno.ktrxpermission.ZPermission
import name.zeno.ktrxpermission.rxPermissions

/**
 * @author 陈治谋 (513500085@qq.com)
 * @since 2017/12/5
 */
internal class AlbumFragment : Fragment() {
  private val resumeSubject = PublishSubject.create<Any>()
  val helper by lazy { PhotoCaptureHelper(this) }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    helper.onActivityResult(requestCode, resultCode, data)
  }

  override fun onResume() {
    super.onResume()
    resumeSubject.onNext(this)
    resumeSubject.onComplete()
  }

  @SuppressLint("MissingPermission")
  fun fromAlbum(): Observable<Bitmap> = (if (isResumed) Observable.just(this) else resumeSubject)
      .flatMap {
        rxPermissions(ZPermission.READ_EXTERNAL_STORAGE)
      }
      .map { if (!it) error("need permission [${ZPermission.READ_EXTERNAL_STORAGE}]") }
      .flatMap {
        val subject = PublishSubject.create<Bitmap>()
        helper.getImageFromAlbum({ path ->
          subject.onNext(BitmapFactory.decodeFile(path))
          subject.onComplete()
        })
        subject
      }

  companion object {
    const val TAG = "name.zeno.qrcode.library.AlbumFragment"
    fun with(fragment: Fragment): AlbumFragment {
      val fm = if (SDK_INT > JELLY_BEAN_MR1) fragment.childFragmentManager else fragment.fragmentManager
      val instance = fm.findFragmentByTag(TAG) as? AlbumFragment
      if (instance != null) return instance

      val new = AlbumFragment()
      fm.beginTransaction().add(new, TAG).commit()
      return new
    }


    fun with(activity: Activity): AlbumFragment {
      val fm = activity.fragmentManager
      val instance = fm.findFragmentByTag(TAG) as? AlbumFragment
      if (instance != null) return instance

      val new = AlbumFragment()
      fm.beginTransaction().add(new, TAG).commit()
      return new
    }
  }
}